var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
// sql
const query = require('../mysql');
// 上传模块
const multer = require('multer');
const upload = multer({
	dest: path.join(__dirname, '../../public/file/project'),
});

// 获取项目信息
router.get('/', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	let { username, searchType } = req.query;
	let inputQuery = req.query.queryInfo.query;
	// 分页效果
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select * from project  where commander like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${username}%`]);
	} else {
		let sqlStr = `select * from project where ${searchType} like ? and commander like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`, `%${username}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from project`;
	let result1 = await query(sqlStr1);

	// 搜索功能
	res.send({ status: 200, result, total: result1[0]['count(*)'] });
});

let projectAddForm;

// 添加项目
router.post('/', async (req, res) => {
	let sqlStr = 'select * from project where no = ?';
	projectAddForm = req.body.projectAddForm;
	let result = await query(sqlStr, [projectAddForm.no]);
	if (result.length != 0) {
		return res.send({ status: 401, message: '项目编号重复' });
	}
	// console.log(req.body);
	res.send({ status: 100, message: '接受项目数据成功' });
});

router.post('/upload', upload.single('file'), async (req, res, next) => {
	file = req.file;
	saveProject(file, req, res);
});

async function saveProject(file, req, res) {
	let {
		name,
		no,
		initial_time,
		closing_time,
		start_time,
		end_time,
		initiation_agency,
		release_unit,
		subject_classification,
		category,
		abstract,
		budget,
		commander,
		participant,
		status,
		remarks,
	} = projectAddForm;
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/essay/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `insert into project(name,no,initial_time,closing_time,start_time,end_time,initiation_agency,release_unit,subject_classification,category,abstract,budget,commander,participant,status,projectfile,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;
	let result = await query(sqlStr, [
		name,
		no,
		initial_time,
		closing_time,
		start_time,
		end_time,
		initiation_agency,
		release_unit,
		subject_classification,
		category,
		abstract,
		budget,
		commander,
		participant,
		status,
		`/file/project/${name}.${extName}`,
		remarks,
	]);
	// console.log(result);
	res.send({ status: 200, message: 'upload project success' });
}

// 修改项目

let projectEditForm;
router.post('/edit', async (req, res) => {
	projectEditForm = req.body.projectEditForm;
	res.send({ status: 100, message: '创建获奖信息成功' });
});
router.post('/edit/upload', upload.single('file'), async (req, res) => {
	file = req.file;
	saveEditFile(file, req, res);
});

async function saveEditFile(file, req, res) {
	let {
		name,
		no,
		initiation_agency,
		initial_time,
		closing_time,
		release_unit,
		start_time,
		end_time,
		subject_classification,
		category,
		abstract,
		budget,
		commander,
		participant,
		status,
		projectfile,
		remarks,
	} = projectEditForm;

	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/project/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});
	let prevFile = path.join(__dirname, `../../public${projectfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});

	let sqlStr =
		'update project set name= ? ,initiation_agency = ? ,initial_time=?,closing_time=?,release_unit=?,start_time=?,end_time=?,subject_classification=?,category=?,abstract=?,budget=?,commander=?,participant=?,status=?,remarks=?,projectfile=? where id =  ?';
	let result = await query(sqlStr, [
		name,
		initiation_agency,
		initial_time,
		closing_time,
		release_unit,
		start_time,
		end_time,
		subject_classification,
		category,
		abstract,
		budget,
		commander,
		participant,
		status,
		remarks,
		`/file/project/${name}.${extName}`,
		projectEditForm.id,
	]);

	res.send({ status: 200, message: 'success' });
}

// 删除项目
router.delete('/', async (req, res) => {
	let reqQuery = req.query;
	// console.log(query);
	let sqlStr = `delete from project where id = ?`;
	let result = query(sqlStr, [reqQuery.id]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});
module.exports = router;
